package com.itheima.demo;

import com.itheima.domain.Emp;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Demo {
    SqlSession session;
    InputStream is;

    @Before
    public void before() throws Exception{
        //1.读取核心配置文件信息
        is = Resources.getResourceAsStream("sql.xml");
        //2.构建SqlSessionFactory工厂对象
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
        //3.通过工厂对象获取SqlSession对象
        session = ssf.openSession();
    }

    @Test
    public void test() throws Exception{
        //4.通过SqlSession对象调用具体方法执行Statement对象

        //统计
        /*int i = session.selectOne("one.count");
        System.out.println("i : " + i);*/

        //查询所有
        /*List<Emp> list = session.selectList("one.findAll");
        System.out.println(list);*/

        //根据编号查询
        /*Emp emp = session.selectOne("one.findById",7369);
        System.out.println(emp);*/

        //模糊查询1
        /*List<Emp> list = session.selectList("one.findLikeName1", "%k%");
        System.out.println(list);*/

        //模糊查询2
        /*List<Emp> list = session.selectList("one.findLikeName2", "k");
        System.out.println(list);*/

        //添加
        /*Emp emp = new Emp();
        emp.setEmpno(4);
        emp.setName("John");
        emp.setJob("manager");
        emp.setHireDate("1999.11.11");
        //emp.setHireDate("1999-11-11");
        //emp.setHireDate("1999/11/11");
        emp.setSal(200.0);
        session.insert("one.insert",emp);*/

        //根据编号修改其他信息
        /*Map map = new HashMap();
        map.put("empno",1);
        map.put("ename","Jack");
        session.update("one.update",map);*/

        //根据编号删除信息
        //session.delete("one.delete",2);

        //统计性别人数
        List<Map> list = session.selectList("one.group");
        Map map = new HashMap();
        for (Map m : list) {
            map.put(m.get("sex"),m.get("total"));
        }
        System.out.println("男: " + map.get("男"));
        System.out.println("女: " + map.get("女"));
    }

    @After
    public void after() throws Exception{
        //5.事务提交
        session.commit();
        //6.释放资源
        session.close();
        is.close();
    }
}
